<template>
  <div class="mt-picker-wrap mt-picker--{{disabled ? 'disabled' : 'inited'}}">
    <div
      class="mt-picker-trigger"
      @tap="onTrigger"
    >
      <block wx:if="{{!inner_value || inner_value.length < 1 || inner_value[0] < 0 || !labeltext}}">
        <div class="mt-picker__init"><slot name="initial"></slot></div>
      </block>
      <block wx:else>
        <div class="mt-picker__content">
          <block wx:if="{{useSlot}}"><slot></slot></block>
          <block wx:else>{{labeltext}}</block>
        </div>
      </block>
      <div class="mt-picker__action"></div>
    </div>


    <mt-popup
      show="{{ showPopup }}"
      position="bottom"
      overlay="{{ true }}"
      bind:clickoverlay="onClickOverlay"
    >
      <div class="u-flex u-aic u-jcsb mt-picker__control">
        <div class="mt-picker__btn mt-picker__cancel" @tap="onCancel">取消</div>
        <div class="mt-picker__btn mt-picker__confirm" @tap="onConfirm">确定</div>
      </div>
      <van-picker
          id="picker"
          columns="{{ inner_columns }}"
          value-key="label"
          @childrenready="onPickerReady"
          @change="onChange"></van-picker>
    </mt-popup>
  </div>
</template>

<script>
  const liveBehavior = require('../../behaviors/live.behavior')

  function isEmpty(value) {
    return !value || value.length < 1 || value[0] < 0
  }

  export default {
    behaviors: [
      'wx://form-field',
      liveBehavior
    ],
    relations: {
      '../mt-liveform/index': {
        type: 'ancestor', // 关联的目标节点应为祖先节点
      },
    },
    properties: {
      indicatorStyle: {
        type: String,
        value: 'height: 50px;'
      },
      pickerStyle: {
        type: String,
        value: 'width: 100%; height: 200px;'
      },
      useSlot: {
        type: Boolean,
        value: false,
      },
      disabled: {
        type: Boolean,
        value: false,
      },
      columns: {
        type: null,
        value: null,
        observer(newVal) {
          let newValIsNull = (Object.prototype.toString.call(newVal) === '[object Null]')
          console.d('multi picker columns', newVal, newValIsNull)
          if (newValIsNull) {
            this.setData({
              inner_columns: []
            })
          } else {
            let parsedValue =  newVal.map( v => {
              if (!v) {
                v = []
              }
              return {
                values: v
              }
            })
            // console.log('columns', parsedValue)
            this.setData({
              inner_columns: parsedValue
            })
          }
          // console.log('columns', newVal, this.data.inner_columns)
        }
      },
      value: {
        type: null,
        value: null,
        observer(newVal) {
          let newValIsNull = (Object.prototype.toString.call(newVal) === '[object Null]')
          if (newValIsNull) {

          } else {
            if (this.data.columns && this.data.columns.length > 1) {
              let picker = this.selectComponent('#picker')
              if (picker) {
                picker.setColumnIndex(0,newVal[0])
                picker.setColumnIndex(1,newVal[1])
                let column1 = picker.getColumnValue(0)
                let column2 = picker.getColumnValue(1)
                console.d('multipicker', newVal, column1, column2)
                this.setData({
                  tmp_value: [
                    column1.value,
                    column2.value
                  ]
                })
                wx.nextTick(() => {
                  this.setData({
                    inner_value: newVal,
                  })
                })
              }
            }
          }
        }
      }
    },
    data() {
      return {
        inner_columns: [],
        inner_value: [],
        tmp_value: [],
        showPopup: false,
        labeltext: ''
      }
    },
    methods: {
      onPickerReady(e) {
        const { picker, children } = e.detail
        console.d(picker, children)
        this.$native.emit('pickerready', {
          picker, context: this
        })
      },
      onTrigger() {
        if (!this.data.disabled) {
          this.setData({
            showPopup: true
          })
        }
      },
      onClickOverlay() {
        this.resetIndex()
        wx.nextTick(() => {
          this.setData({
            showPopup: false
          })
        })
      },
      onCancel() {
        this.resetIndex()
        wx.nextTick(() => {
          this.setData({
            showPopup: false
          })
        })
      },
      getLabel(value) {
        let columns1 = this.data.inner_columns[0].values
        let columns2 = this.data.inner_columns[1].values
        console.d('multi selector getLabel', columns1, columns2)
        return [
          columns1[value[0]].label,
          columns2[value[1]].label
        ].join()
      },
      setLabel(value){
        this.setData({
          labeltext: this.getLabel(value)
        })
      },
      onConfirm() {
        if (this.data.tmp_value &&
            this.data.tmp_value.length > 0
        ) {
          // console.log(this.data.tmp_value)
          this.setData({
            inner_value: this.data.tmp_value,
            labeltext: this.getLabel(this.data.tmp_value),
            showPopup: false
          })
          this.fireChange(this.data.tmp_value)
        } else {
          // console.log(isEmpty(this.data.inner_value))
          if (isEmpty(this.data.inner_value)) {
            // console.log(columns1, columns2)
            this.setData({
              tmp_value: [0, 0],
              inner_value: [0, 0],
              labeltext: this.getLabel([0, 0]),
              showPopup: false
            })
            this.fireChange([0, 0])
          }
        }
      },
      fireChange(newVal) {
        this.mtLiveCall(newVal)
        this.$native.emit('change', {
          value: newVal
        })
      },
      onChange(e) {
        const { picker, value, index } = e.detail;
        // picker.setColumnValues(1, citys[values[0]]);
        let detailValue = e.detail.value
        console.d('e', detailValue, e)
        if (Array.isArray(detailValue) && detailValue.length > 0) {
          this.setData({
            tmp_value: detailValue.map( v => v.value)
          })
          this.$native.emit('live-change', {
            picker, value, index
          })
          // console.log('select change', e.detail, e.detail.value[0], this.data.inner_value[0])
          // console.log(this.data.tmp_value)
        } else {
          console.error('multi picker error', detailValue)
        }
      },
      resetIndex() {
        let picker = this.selectComponent('#picker')
        if (picker) {
          picker.setColumnIndex(0, this.data.inner_value[0])
          picker.setColumnIndex(1, this.data.inner_value[1])
        }
      }
    },
  }
</script>

<style lang="less">
</style>
